<template>
  <div class="graph" >
    <div class="main">
    
      <div class="input" id="content" >
        
        <el-input  placeholder="请输入内容" 
         @keyup.enter.native="entitySearch()" v-model="inputQuery" v-show="this.showPNG">
         
          <img id="record_btn" @click="record()" slot="suffix" src="../../../assets/yuyin.png" alt="录音" />

          <el-button  slot="append" icon="el-icon-search" @click="entitySearch(true)">
          </el-button>
        </el-input>
        <div class="luyin" style="background-color: #ffffff;border-radius: 5px;" v-show="!this.showPNG">
          <el-input type="textarea"  rows="4"  v-model="textModel"  :disabled="this.disabled"
          style="margin: 10px;width: 72%;" id="result_p" placeholder="正在聆听..."></el-input>
          
          <img id="record_btn" style="width: 60px;height: 65px;margin: 20px 5px;" 
              @click="record()" slot="suffix" src="../../../assets/recording.gif" alt="录音"/>
        </div>
      </div>
      <!-- 图谱中心 -->
      <GraphQueryBoard
        ref="queryBoard"
        @init-property="initPropertyHandler"
      ></GraphQueryBoard>

      <el-card v-show="this.showAnswer" >
        <p style="text-align: center;justify-content: center;" v-if="this.answer==''">正在推理中</p>
        <i class="el-icon-loading" v-if="this.answer==''"></i>
        <p style="white-space: pre-line" id="typewriter" v-else>{{ this.answer }}</p>
      </el-card>
      
      <img  class="dialog" src="../../../assets/tycm-3.gif"/>
      <div style="color: #ffffff;right: 70px;bottom:70px;position: fixed;">推理助手</div>
    </div>

    <el-popover placement="right"  trigger="click">
      <div>
       
        <img id="record_btn" 
            @click="record()" slot="suffix" src="../../../assets/recording.gif" alt="录音"/>
      </div>
    </el-popover>

  
  </div>

  
</template>

<script >
import GraphQueryBoard from './GraphQueryBoard'
import {mapGetters, mapActions} from 'vuex'
import {getEntity} from '../../../api/http.js'
import {get} from '../record.js'
import {chat} from '../../../api/http.js'
import {recordURL} from '../../../api/config'
// Vue.use(get)

//取消选中并且取消右键操作
document.body.onselectstart =
  document.body.oncontextmenu =
    function () {
      return false; //取消浏览器默认操作
    };

var is_recording = false;
var host = location.origin;
var recorder;


export default {
  name: 'GraphQuery',
  props: {
    // projectId: {
    //   type: Number
    // },
    nodes: {
      type: Array
    },
    links: {
      type: Array
    }
  },
  components: {
    GraphQueryBoard
  },
  data() {
    return {
      projectId: 0,
      inputQuery: '',
      projectInfo: {},
      graphData: null,
      graphProperty: {
        layoutMode: 'FORCE',
        nodeScale: null
      },
      dtSearch: () => {
      },
      dSearch: () => {
      },
      entityData:'',
      showPNG: true,
      result: '',
      textModel: '',
      disabled: true,
      answer: '',
      showAnswer: false
    }
  },
  computed: {
    ...mapGetters(['userId'
      // 'graphData',
      // 'projectInfo',
    ]),
    
  },
  methods: {
    ...mapActions({
      getProjectInfoAct: 'getProjectInfo',
      getProjectGraphDataAct: 'getProjectGraphData',
      entityQueryGlobal:'entityQueryGlobal',
      entityQueryGlobalMultiName:'entityQueryGlobalMultiName'
    }),
    /***** 重新挂载图谱 *****/
    mountGraphData(data) {
      console.log('projectInfo:', this.projectId)
      console.log('daataaaaa'+data)
      this.origin = deepCopy(data)
      // this.projectInfo = deepCopy(projectInfo)
      const projectInfo = this.getProjectInfoAct(this.projectId)
      const {nodes, links, layouts} = data
      this.nodes = [...nodes]
      console.log("项目所有节点849561：" + JSON.stringify(this.nodes))
      this.links = [...links]
      this.layouts = deepCopy(layouts)
      this.init()
      this.flags.loaded = true
    },
    entitySearch() {
      if(this.inputQuery === '') {
        this.$message.warning("内容不能为空！")
      } 
      else {
        this.showAnswer = true
        this.answer = ''
        // 实体识别
        getEntity(this.inputQuery).then( res =>{
          console.log('res',res);
          this.entityData = res;
          console.log('this.entityData',this.entityData);
          
          if(this.entityData === ''){
            // this.graphData = null
            // const nodeSearch = this.$refs.queryBoard
            // nodeSearch.mountGraphData(this.graphData)
            this.$message.warning('图谱暂无结果！')
            const message = "你是一个面向作战目标、作战规则、武器装备、体系对抗领域的问题推理求解助手，" 
              + "请你根据问题给出详细推理过程，你的回答的格式是问题、推理过程、结论、参考信息、理论依据。"
              + "你遵守的规则是：1、在你的回答中不要出现重复信息；2、在你的回答中不要出现英文，你可以把英文翻译成中文；3、在你的回答中不要出现给你的JSON格式信息；"
              + "4、给出的答案越详细越好，最好分步骤并有理论依据；5、违背以上规则会给你的答案减分。需要你帮助求解的问题是：“"+ this.inputQuery 
              + "”。。以下是为你提供的JSON格式的参考信息：{},请你解析并重新润色形成最终的描述文本类参考信息。" 
            chat({
                    question: message,
                    history: [],
                  }).then(res =>{
                    this.answer = res.data.response
                  } )
          }else {
            const data = {
              "entityId": 0,
              "entityName": this.entityData,
              "fuzzyQuery": true,
              "projectId": 0
            }
            // 图谱结果
            this.entityQueryGlobalMultiName(data).then((res) => {
            console.log("搜索结果"+JSON.stringify(res))
            if(res.nodes.length === 0){
              this.graphData = res
              const nodeSearch = this.$refs.queryBoard
              nodeSearch.mountGraphData(this.graphData)
              this.$message.warning('图谱暂无结果！')
              const message = "你是一个面向作战目标、作战规则、武器装备、体系对抗领域的问题推理求解助手，" 
                + "请你根据问题给出详细推理过程，你的回答的格式是问题、推理过程、结论、参考信息、理论依据。"
                + "你遵守的规则是：1、在你的回答中不要出现重复信息；2、在你的回答中不要出现英文，你可以把英文翻译成中文；3、在你的回答中不要出现给你的JSON格式信息；"
                + "4、给出的答案越详细越好，最好分步骤并有理论依据；5、违背以上规则会给你的答案减分。需要你帮助求解的问题是：“"+ this.inputQuery 
                + "”。。以下是为你提供的JSON格式的参考信息：{name:'',group:'',properties:{}},请你解析并重新润色形成最终的描述文本类参考信息。" 
              chat({
                    question: message,
                    history: [],
                  }).then(res =>{
                    this.answer = res.data.response
                  } )
              
            }else{
              this.graphData = res
              const nodeSearch = this.$refs.queryBoard
              nodeSearch.mountGraphData(this.graphData)
              // 进行对话 
              // var pps = ''
              // var p = res.nodes[0]['properties']
              // console.log("ppp",p)
              // for (const [key, value] of Object.entries(p)) {
              //   pps += key + "：" + value + ","
              // }
              // console.log('pps',pps)
              // const graphInfo = res.nodes[0]['name'] + pps
              const graphInfo = res.nodes[0]
              // const graphInfo1 = res.nodes[2]
              console.log('graphInfo',JSON.stringify(graphInfo))
              // 推理助手
              this.showAnswer = true
              this.answer = ''
              // const message = this.inputQuery
              const message = "你是一个面向作战目标、作战规则、武器装备、体系对抗领域的问题推理求解助手，" 
                + "请你根据问题给出详细推理过程，你的回答的格式是问题、推理过程、结论、参考信息、理论依据。"
                + "你遵守的规则是：1、在你的回答中不要出现重复信息；2、在你的回答中不要出现英文，你可以把英文翻译成中文；3、在你的回答中不要出现给你的JSON格式信息；"
                + "4、给出的答案越详细越好，最好分步骤并有理论依据；5、违背以上规则会给你的答案减分。需要你帮助求解的问题是：“"+ this.inputQuery 
                + "”。以下是为你提供的JSON格式的参考信息：{name:" + graphInfo['name'] + ';group:' + graphInfo['group'] + ';properties:' 
                + JSON.stringify(graphInfo['properties']) + "},请你解析并重新润色形成最终的描述文本类参考信息。" 
              chat({
                    question: message,
                    history: [],
                  }).then(res =>{
                    this.answer = res.data.response
                  } ) 
            }
          })

          }
          // this.entityQueryGlobal(data).then((res) => {
          //   console.log("搜索结果"+JSON.stringify(res))
          //   if(res.nodes.length === 0){ 
          //     this.$message.warning('查无结果！')
          //   }else{
          //     this.graphData = res
          //     const nodeSearch = this.$refs.queryBoard
          //     nodeSearch.mountGraphData(this.graphData)
          //   }
          // })
          
          
        }),err=>{
            console.log(err);
        }; 
      }    
    },
    initPropertyHandler(name, value) {
      // console.log(`[InitProperty] ${name}`)
      this.graphProperty[name] = value
    },
    record() {
      if (is_recording) {
        is_recording = false;
        this.stopRecording()
        document.getElementById('record_btn')
        this.showPNG = true
        // .src = '../../../assets/record.png'
      } else {
        is_recording = true;
        this.disabled = false
        this.startRecording()
        document.getElementById('record_btn')
        this.showPNG = false
        this.disabled = true
        // .src = '../../../assets/recording.gif'
        }
    },
    // 开始录音
    startRecording() {
      // let url = 'ws://' + location.hostname + ':5001';
      let url = recordURL;
      console.log("url",url)
      const textarea = document.getElementById('result_p')
      console.log("textarea",textarea)
      console.log("textarea",textarea.value)
      get(function (record) {recorder = record;}, url, textarea);
    },
    // 停止录音
    stopRecording() {
     this.result = recorder.stop(); 
     console.log("最后的结果",this.result.value) 
     this.inputQuery = this.result.value
    },

  },
  async mounted() {
    
    const {search, userId} = this
    
    // const projectId = this.projectId
    // if (projectId !== NaN){
    //   const projectInfo = await this.getProjectInfoAct(projectId)
    //   let key
      
    //   if (!projectInfo) {
    //     // warning
    //     return
    //   }
    //   this.projectInfo = projectInfo
    // }
    

    //初始化图谱数据
    const graphData = await this.getProjectGraphDataAct(projectId)

    // const graphData = deepCopy(_graphData)
    if (!graphData) {
      // warning
      return
    }
    this.graphData = graphData
    console.log("初始化图谱数据结果09123012："+JSON.stringify(this.graphData))

    const nodeSearch = this.$refs.queryBoard
    console.log(nodeSearch)
    nodeSearch.mountGraphData(this.graphData)

    console.log('graphData:', graphData)
  }
}
</script>

<style scoped>
.graph {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: stretch;
  overflow: hidden;
  
}

.graph > .main {
  flex: 1;
  position: relative;
  /* background-image: url('../assets/graphbg.png');
  opacity: 0.9; 
  background-repeat: no-repeat;
  background-position: center;
  background-size:100% 100%; */
}

.graph > .main > .title {
  position: absolute;
  left: 40px;
  top: 20px;
  border-radius: 20px;
  box-shadow: 1px 1px 1px 0px slategray;
  background-color: #ffffff;
  height: 40px;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.graph > .editor {
  border-left: 1px solid #bbbbbb;
  box-sizing: border-box;
  transition: width 1s ease-out;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  overflow: auto;
}

.graph > .editor.open {
  width: 350px;
}

.graph > .editor.close {
  width: 0;
}

.input { 
  width: 40%;
  position: fixed;
  top:7%;
  left: 29%;
}
.input .el-input .el-input__inner  {
  border-radius: 50px;
}
#content img {
    cursor: pointer;
    height: 20px;
    transition: transform 0.2s;
    width: 20px;
    margin-top: 9px;
    margin-right: 5px;
}
.luyin .el-textarea__inner {
     border: 0px solid #DCDFE6 !important;
     font-size: 20px !important;
}
.main .el-card{
  /* padding: 20px 0px !important; */
  bottom: 200px;
  right: 48px;
  width: 320px;
  /* height: 190px; */
  max-height: 510px;
  position: fixed;
  background-color: rgba(255,255,255,0.2);
  color: #ffffff;
  border: 0;
  font-size: 14px;
  font-weight: 400;
  font-family: 'Courier New', Courier, monospace;
  text-align: left;
  overflow-y: scroll;
}
.main .dialog {
  bottom: 90px;
  right: 47px;
  width: 110px;
  height: 100px;
  position: fixed;
  /* opacity: 0.8; */
}
/* .dialogbg {
  bottom: 180px;
  right: 10px;
  width: 400px;
  position: fixed;
  background-image: url('../../../assets/dialog_bg.png');
  background-size: 100% auto;
  background-repeat:no-repeat;
  opacity: 0.2;
} */

.main .el-card::-webkit-scrollbar {
    width: 4px;
}
.main .el-card::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0,0,0,0.2);
}
.main .el-card::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0,0,0,0.1);}


.main .el-icon-loading{
  /* margin-top: 19%; */
  margin-left: 47%;
  font-size: 24px;
}
/* 尝试实现打字机效果 */
/* #typewriter{
    font-size: 15px;
    width: 0;
    height: 18px;
    border-right: 1px solid darkgray;
    animation: write 4s steps(14) forwards,
      blink 0.5s steps(1) infinite;
      overflow: hidden;
  }
  @keyframes write {
    0% {
      width: 0;
    }
    100% {
      width: 280px;
    }
   
  }
  @keyframes blink {
    50% {
      border-color: transparent; 
    }
  } */
</style>
